 import Honey from '../../utils/honey';
 import Event from '../../utils/event'


 const app = getApp();
 const honey = new Honey();
 const event = new Event();
 Page({

   /**
    * 页面的初始数据
    */
   data: {
     comboId: '',
     combo: {
       commtent_num: 0
     },
     user: {},
     payMoney: 0,
     paymentArray: {},
     paymentShow: false,
     disabled:true,//余额支付是否可用参数
     payment: 2, //支付方式：2为微信支付，其他为余额支付
     longitude: '',
     latitude: '',
     searchName: '',
     organizationList: [],
     showContent: {
       detail: true,
       notes: false,
     },
     top: false,
     scrollTop: 0,
     toPageTop: 10000,
     scrollRoll: '',
     swiperShow: 1,
     phone: '',
     phoneUntying: false, //手机解绑框
     message: '', //手机已存在绑定账号提示信息
     unPhone: '',
     imageList: [], //商品详情图片
     openShow: true, //页面加载幕布显示隐藏
     items: [{
         name: '2',
         value: '微信支付',
         checked: 'true'
       },
       {
         name: '1',
         value: '余额支付'
       },
     ], //支付方式单选内容
   },

   /**
    * 生命周期函数--监听页面加载
    */
   onLoad: function(options) {
     wx.checkSession({
       fail: function(res) {
         wx.login({
           success: res => {
             honey.post({
               alias: 'minSessionKey',
               data: {
                 code: res.code
               },
               success: function(res) {
                 wx.setStorageSync('sessionKey', res.data.data.result.session_key)
               }
             })
             // 发送 res.code 到后台换取 openId, sessionKey, unionId
           }
         })
       }
     })
     const comboId = options.id;
     const that = this;
     if (wx.getStorageSync('phone')) {
       that.setData({
         phone: wx.getStorageSync('phone'),
       })
     }
     that.setData({
       comboId: comboId,
     })
     that.getCommentList();
     if (options.check_code && !wx.getStorageSync('user')) {
       wx.setStorageSync('checkCode', options.check_code);
       var pages = getCurrentPages(); //获取加载的页面
       var currentPage = pages[pages.length - 1]; //获取当前页面的对象
       var url = `/${currentPage.route}`; //当前页面url
       var toUrl = `${url}?id=${currentPage.options.id}`; //如果要获取url中所带的参数可以查看options
       console.log(toUrl);
       if (!wx.getStorageSync('user')) {
         wx.setStorageSync('pagesUrl', toUrl)
         wx.switchTab({
           url: '/pages/index/index',
         })
         return;
       }
     }
     wx.showLoading({
       title: "加载中..."
     });
     wx.getLocation({
       type: 'gcj02',
       complete: function(res) {
         that.getComboDetail(res);
         that.setData({
           longitude: res.longitude ? res.longitude : '',
           latitude: res.latitude ? res.latitude : ''
         })
       },
       fail() {
         that.getComboDetail({
           longitude: '',
           latitude: ''
         });
       },
     })
   },

   /**
    * 生命周期函数--监听页面初次渲染完成
    */
   onReady: function() {
     const that = this;
     // const user = honey.checkLogin('/pages/combo/detail', false);
     // that.setData({
     //   user: user
     // })

   },

   /**
    * 生命周期函数--监听页面显示
    */
   onShow: function() {
     const that = this;
     const user = wx.getStorageSync('user');
     that.setData({
       user: user,
       paymentShow: false,
     })
   },

   /**
    * 生命周期函数--监听页面隐藏
    */
   onHide: function() {

   },

   /**
    * 生命周期函数--监听页面卸载
    */
   onUnload: function() {

   },

   /**
    * 页面相关事件处理函数--监听用户下拉动作
    */
   onPullDownRefresh: function() {},

   /**
    * 页面上拉触底事件的处理函数
    */
   onReachBottom: function() {
     const that = this;
     if (that.data.showContent.notes) {
       that.showContent({
         currentTarget: {
           dataset: {
             contentName: "detail"
           }
         }
       })
     }
   },

   /**
    * 用户点击右上角分享
    */
   showContent: function(e) {
     const that = this;
     const flag = e.currentTarget.dataset.contentName;
     const showContent = {
       detail: false,
       notes: false,
     }
     showContent[flag] = true;

     if (that.data.scrollY > that.data.toPageTop) {
       that.setData({
         showContent: showContent,
       })

       setTimeout(() => {
         that.setData({
           scrollTop: that.data.toPageTop
         })
       }, 200)

     } else {
       that.setData({
         showContent: showContent,
       })

     }
   },
   onShareAppMessage: function() {
     const that = this;
     return {
       title: `推荐您:${that.data.combo.goods_name}`,
       path: `/pages/combo/detail?id=${that.data.comboId}&check_code=${that.data.user.check_code}`
     }
   },
   getComboDetail: function(pos) {
     const that = this;
     honey.post({
       alias: 'getGoodsInfo',
       data: {
         goods_id: that.data.comboId,
         lng: pos.longitude ? pos.longitude : '',
         lat: pos.latitude ? pos.latitude : ''
       },
       success: function(res) {
         let combo = res.data.data.goodsInfo;
         combo.content = combo.content.replace('<br />', '').replace(/\<img/gi, '<img style="max-width:100%;height:auto;margin:0 auto;display:block;" ').replace('<br/></p>', '</p>');
         combo.notice = combo.notice.replace('<br />', '').replace(/\<img/gi, '<img style="max-width:100%;height:auto;margin:0 auto;display:block;" ').replace('<br/></p>', '</p>');
         let payMoney = (combo.only_price * 1 - combo.max_health * 1).toFixed(2);
         let disabled = that.data.user.info.amount >= payMoney ? false : true;
         that.setData({
           combo: combo,
           organizationList: res.data.data.storeList,
           imageList: res.data.data.imageList,
           payMoney: payMoney,
           disabled
         })

         if (!combo.video) {
           that.setData({
             swiperShow: 2,
           })
         }

         setTimeout(() => {
           try {
             wx.createSelectorQuery().select('#navTab').fields({
               rect: true
             }, function(res) {
               that.setData({
                 toPageTop: res.top,
                 scrollRoll: 'true'
               })
             }).exec()
           } catch (e) {
             console.log(e)
           } finally {
             that.setData({
               openShow: false
             })
             wx.hideLoading();
           }
         }, 300)

       }
     })

   },
   toBuy: function() {
     const that = this;
     if (!that.data.user) {
       const user = honey.checkLogin('/pages/combo/detail?id=' + that.data.comboId, false);
       return;
     }
     event.emit('refreshUserInfo', 'userInfo');
     wx.showLoading({
       title: '请稍后',
       mask: true
     })
     honey.post({
       alias: 'getUserInfo',
       success: function(res) {
         const user = Object.assign(wx.getStorageSync('user'), res.data.data);
         wx.setStorageSync('user', user);

         that.setData({
           user: user,
           paymentShow: true,
         })
         wx.hideLoading();
       }
     })
   },

   saveOrder: function() {
     const that = this;
     wx.showLoading({
       title: '支付中',
       mask: true
     })
     wx.login({
       success: function(res) {
         if (res.code) {
           honey.post({
             alias: 'createOrder',
             data: {
               goods_id: that.data.comboId,
               health_pay: that.data.combo.max_health,
               pay_type: that.data.payment == 2 ? 'wx_pay' : 'amount_pay'
             },
             success: function(res) {
               if (!res.data.data.payParam) {
                 let orderId = res.data.data.order_sn;
                 wx.navigateTo({
                   url: '/pages/pay/paySuccess?id=' + orderId,
                 })
               } else {
                 var payParam = res.data.data.payParam;
                 wx.requestPayment({
                   timeStamp: payParam.timeStamp,
                   nonceStr: payParam.nonceStr,
                   package: payParam.package,
                   signType: payParam.signType,
                   paySign: payParam.paySign,
                   success: function() {
                     event.emit('refreshUserInfo', 'userInfo');
                     wx.navigateTo({
                       url: '/pages/pay/paySuccess?id=' + res.data.data.order_sn,
                     })
                   },
                   fail: function(res) {
                     event.emit('refreshUserInfo', 'userInfo');
                     wx.showToast({
                       title: '支付失败',
                       image: '/res/images/icon-shibai.png'
                     })
                     setTimeout(() => {
                       wx.navigateTo({
                         url: '/pages/mine/myPurchase',
                       })
                     }, 1500)
                   }
                 })
               }
             },
             complete: function() {
               event.emit('refreshUserInfo', 'userInfo');
               wx.hideLoading();
             }
           })
         } else {
           wx.showToast({
             title: '登录失败' + res.errMsg,
           })
         }
       }
     })
   },
   closeCashier: function() {
     const that = this;
     that.setData({
       paymentShow: false
     })
   },
   positionTop: function(e) {
     const that = this;
     //  console.log(e.detail.scrollTop);
     //  console.log(that.data.toPageTop);
     if (e.detail.scrollTop > that.data.toPageTop) {
       that.setData({
         top: true,
         scrollY: e.detail.scrollTop
       })
     } else {
       that.setData({
         top: false,
         scrollY: e.detail.scrollTop
       })
     }
   },
   swiperSwitch: function(e) {
     const that = this;
     that.setData({
       swiperShow: e.currentTarget.dataset.value
     })
   },

   getPhoneNumber: function(e) {
     console.log(111)
     const that = this;
     console.log(e);
     if (e.detail.errMsg == "getPhoneNumber:ok") {
       console.log(222)
       const phone = e.detail;
       honey.post({
         alias: 'bindUserPhone',
         data: {
           encrypt: phone.encryptedData,
           iv: phone.iv,
           session_key: wx.getStorageSync('sessionKey')
         },
         success: function(res) {
           if (res.data.data.had_bind == 1) {
             that.setData({
               phoneUntying: true,
               unPhone: res.data.data.mobile,
               message: res.data.message
             })
           } else {
             wx.setStorageSync('phone', res.data.data.userInfo.mobile);
             that.setData({
               phone: res.data.data.userInfo.mobile
             })
             that.toBuy();
           }
         }
       })
     }
   },

   untyingPhone: function() {
     const that = this;
     honey.post({
       alias: 'unbindUserPhone',
       data: {
         mobile: that.data.unPhone
       },
       success: function(res) {
         wx.showToast({
           title: '绑定成功',
           icon: 'none'
         })
         wx.setStorageSync('phone', that.data.unPhone);
         that.setData({
           phoneUntying: false,
         })
         that.toBuy();
       }
     })
   },

   //关闭手机绑定框
   clearUntyingPhone: function() {
     that.setData({
       phoneUntying: false,
     })
   },

   //获取评价列表数据
   getCommentList: function() {
     const that = this;
     that.setData({
       isLoad: false
     })
     honey.post({
       alias: 'commentList',
       data: {
         page: 1,
         page_size: 5,
         goods_id: that.data.comboId,
       },
       success: function(res) {
         that.setData({
           commentList: res.data.data.comment_list,
         })
       }
     })
   },

   //点击打开图片
   previewImage: function(e) {
     const that = this;
     const image = e.currentTarget.dataset.image;
     console.log(image);
     const index = e.currentTarget.dataset.index;
     console.log(index);
     wx.previewImage({
       current: image, // 当前显示图片的http链接
       urls: that.data.commentList[index].smeta.image // 需要预览的图片http链接列表
     })
   },

   //支付方式选择事件
   radioChange: function (e) {
     const that=this;
     that.setData({
       payment: e.detail.value
     })
   }
 })